#include "TaskPerformer.h"
#include "../Time.h"

mtBEGIN(TaskPerformer)
	mtBASE(ECS::Component);
	mtMETHOD(onUpdate);
mtEND


bool TaskPerformer::hasTask() const
{
	return _currentTask != nullptr;
}

Task* TaskPerformer::getCurrentTask() const
{
	return _currentTask;
}

TaskPerformer::TaskPerformer() :
	_currentTask(nullptr)
{

}

TaskPerformer::~TaskPerformer()
{

}

void TaskPerformer::onUpdate()
{
	update(Time::deltaTime);
}

void TaskPerformer::update( float dt )
{
	if (_currentTask == nullptr && !_taskQueue.empty())
	{
		_currentTask = _taskQueue.front();
		_taskQueue.pop();

		_currentTask->start();
		eventTaskStarted(_currentTask);
	}

	if (_currentTask)
	{
		if (_currentTask->getState() == Task::Active)
		{
			_currentTask->update(dt);
		}

		switch (_currentTask->getState())
		{
		case Task::Done:
			_currentTask->done();
			eventTaskDone(_currentTask);
			eventTaskFinilized(_currentTask);
			_currentTask = nullptr;
			break;
		case Task::Interrupted:
			_currentTask->interrupt();
			eventTaskInterrupted(_currentTask);
			eventTaskFinilized(_currentTask);
			_currentTask = nullptr;
			break;
		default:
			break;
		}
	}
}

void TaskPerformer::addTask( Task* task, bool startImmediately /*= true*/ )
{
	_taskQueue.push(task);
}

